const express = require("express");
const router = express.Router();
const salaryDao = require("../database/SalaryDao");

router.post("/months", async (req, res) => {
    try {
        const { userId } = req.body;
        const months = await salaryDao.querySalaryMonthsByUserId(userId);
        res.send({ code: 2000, msg: '查询成功', data: months });
    } catch (error) {
        res.send({ code: 4001, msg: '查询失败', data: null });
    }
})

router.post("/load", async (req, res) => {
    try {
        const { userId, month } = req.body;

        if (!userId || !month) {
            return res.status(400).json({
                code: 4001,
                msg: "userId 和 month 是必填参数",
                data: null
            });
        }

        // 查询各项工资数据
        const baseSalary = await salaryDao.queryBaseSalary(userId);
        const attendanceMoney = await salaryDao.queryAttendanceMoney(userId, month);
        const allowanceMoney = await salaryDao.queryAllowanceMoney(userId, month);
        const totalSalary = await salaryDao.queryTotalSalary(userId, month);

        // 构造返回数据
        const data = {
            userId,
            month,
            baseSalary,
            attendanceMoney,
            allowanceMoney,
            totalSalary
        };

        // 成功响应
        res.json({
            code: 2000,
            msg: "查询成功",
            data
        });

    } catch (err) {
        console.error("Error fetching salary data:", err);
        res.status(500).json({
            code: 5000,
            msg: "服务器内部错误",
            data: null
        });
    }
});
router.post("/annual-summary", async (req, res) => {
    try {
        const { userId } = req.body;

        if (!userId) {
            return res.status(400).json({
                code: 4001,
                msg: "userId 是必填参数",
                data: null
            });
        }

        // 查询员工本年度的工资总和
        const summary = await salaryDao.queryAnnualSummary(userId);

        // 计算年终奖金
        const annualBonus = summary.totalSalary / 12;

        // 构造返回数据
        const data = {
            totalSalary: summary.totalSalary || 0,
            annualBonus: annualBonus
        };

        // 成功响应
        res.json({
            code: 2000,
            msg: "查询成功",
            data
        });

    } catch (err) {
        console.error("Error fetching annual summary data:", err);
        res.status(500).json({
            code: 5000,
            msg: "服务器内部错误",
            data: null
        });
    }
});

module.exports = router;